package cn.xdd.servlet.usermange;


import cn.xdd.dao.UserDao;
import cn.xdd.dbutil.DbUtil;
import cn.xdd.entity.User;
import com.google.gson.Gson;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author user_xdd
 * @Date 2022-03-28 13:23
 * @description 用户信息服务
 * @return
 */
@WebServlet(urlPatterns = "/usermange/UserInfoServlet")
public class UserInfoServlet extends GenericServlet {

    private static final Logger LOGGER = Logger.getLogger(UserInfoServlet.class);
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";
    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

      @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");//设置请求中文编码
        response.setContentType("text/html;charset=utf-8");//设置响应中文编码
        UserDao userDao =  new UserDao();
        HttpSession session = request.getSession();
        Gson gson=new Gson();
        String option = request.getParameter("option");
         LOGGER.debug("    option:"+option);
          try {

        if(option==null){
            //注册操作
            // 检测是否为多媒体上传  验证表单有没有配置enctype=multipart/form-data
            if (!ServletFileUpload.isMultipartContent(request)) {
                // 如果不是则停止
                PrintWriter writer = response.getWriter();
                writer.println("Error: 表单必须包含 enctype=multipart/form-data");
                writer.flush();
                return;
            }

            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            // 设置临时存储目录
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
            // 创建上传工具对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 设置最大文件上传值
            upload.setFileSizeMax(MAX_FILE_SIZE);
            // 设置最大请求值 (包含文件和表单数据)
            upload.setSizeMax(MAX_REQUEST_SIZE);
            // 中文处理
            upload.setHeaderEncoding("UTF-8");
            // 构造临时路径来存储上传的文件
            // 这个路径相对当前应用的目录
            String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;

            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            User user = new User();//创建需要添加的用户对象

            // 解析请求的内容提取文件数据+表单数据 解析之后填充到User对象
            try {

                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    // 迭代文件数据+表单数据
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {//不是表单而是文件
                            //将原本的文件名就作为上传到服务器的文件
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            // 在控制台输出文件的上传路径
                            System.out.println(filePath);
                            // 保存文件到硬盘
                            item.write(storeFile);
                            //要将文件的路径设置到User对象内 以便将路径保存到数据库
//                                user.setPhoto("upload/" + fileName);
                        } else {//遇到的是表单参数
                            System.out.println("参数名:" + item.getFieldName());
                            System.out.println("参数值:" + item.getString("utf-8"));//参数值处理中文编码

                            //将每个参数值填充到user对象里
                            if (item.getFieldName().equals("user_nickname")) {
                                user.setUser_nickname(item.getString("utf-8"));
                            }
                            if (item.getFieldName().equals("user_password")) {
                                user.setUser_password(item.getString("utf-8"));
                            }
//                                if (item.getFieldName().equals("name")) {
//                                    user.setName(item.getString("utf-8"));
//                                }
                            if (item.getFieldName().equals("user_email")) {
                                user.setUser_email(item.getString("utf-8"));
                            }
//                                if (item.getFieldName().equals("birthday")) {
//                                    //表单传递的数据为格式化的日期字符串 转为对应的日期对象
//                                    String str_date = item.getString("utf-8");//yyyy-mm-dd
//                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
//                                    Date birth = sdf.parse(str_date);
//                                    user.setBirthday(birth);
//                                }
                            if (item.getFieldName().equals("user_phone")) {
                                user.setUser_phone(item.getString("utf-8"));
                            }
                            if (item.getFieldName().equals("sex")) {
                                user.setUser_sex(item.getString("utf-8"));
                            }

                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                //接收文件 参数出现异常
                response.sendRedirect("/message.html");
                return;//如果异常出现也就直接跳出过程 不进行数据库保存了
            }

            LOGGER.debug("    user:"+user);
            //保存当前用户对象   dao方法内的异常抛出到servlet来处理
            boolean result = false;
            boolean b = userDao.addUser(user);
            if(b){
                String url="/usermange/UserInfoServlet?option=querryUser&inputEmail="+user.getUser_email()+"&pwd="+user.getUser_password();
                 LOGGER.debug(" 成功   url:"+url);
                request.getRequestDispatcher(url).forward(request,response);
                return;
            }
            else {
                response.sendRedirect("/login.html");
            }

            return;
        }

        switch (option){
            case "querryUser":{
                String email = request.getParameter("inputEmail");
                String pwd = request.getParameter("pwd");
                LOGGER.debug("    email:" + email);
                LOGGER.debug("    pwd:" + pwd);
                User user = null;
//                查询
                user = userDao.login(email, pwd);

                LOGGER.debug("    user:" + user);
                if (user == null) {
                    response.getWriter().println("<script>alert('失败')</script>");
                    response.sendRedirect("/login.html");
                } else {
                    response.getWriter().println("<script>alert('成功')</script>");
                    session.setAttribute("loginUser",user);
                    response.sendRedirect("/index.html");
                }
            }
            case "checkUsername":{
                String username = request.getParameter("username");
                LOGGER.debug("    username:" + username);
//                查询数据库
                boolean b = userDao.checkUserName(username);
                LOGGER.debug("  false表示没有重复  b:" + b);
//                没有重复的
                if (!b) {
                    response.getWriter().print("true");
                } else {
                    response.getWriter().print("false");
                }
                break;
            }
            case "checkEmail":{
                String Email = request.getParameter("Email");
                LOGGER.debug("    Email:" + Email);
//                查询数据库 有重复为true
                boolean b = userDao.checkUserEmail(Email);
                LOGGER.debug("    b:" + b);
//                没有重复的
                if (!b) {
                    response.getWriter().print("true");
                } else {
                    response.getWriter().print("false");
                }
                break;
            }
            case  "checkUserTele":{
                String Tele = request.getParameter("Tele");
                LOGGER.debug("    Tele:" + Tele);
//                查询数据库 有重复为true
                boolean b = userDao.checkUserTele(Tele);
                LOGGER.debug("    b:" + b);
//                没有重复的
                if (!b) {
                    response.getWriter().print("true");
                } else {
                    response.getWriter().print("false");
                }
                break;
            }
            case "checkTele":{
                String Tele = request.getParameter("Tele");
                LOGGER.debug("    Tele:" + Tele);
//                查询数据库 有重复为true
                boolean b = userDao.checkUserTele(Tele);
                LOGGER.debug("    b:" + b);
//                没有重复的
                if (!b) {
                    response.getWriter().print("true");
                } else {
                    response.getWriter().print("false");
                }
                break;
            }
            case "getloginUser":{
                User user = (User) session.getAttribute("loginUser");
                String json = gson.toJson(user);
                response.getWriter().println(json);
                 LOGGER.debug("    json:"+json);
                break;
            }
            case "updateloginUser":{
                User newUser=new User();
                int id= Integer.parseInt(request.getParameter("user_id"));

                newUser.setUser_id(id);
                newUser.setUser_nickname(request.getParameter("user_nickname"));
                newUser.setUser_phone( request.getParameter("user_phone"));
                newUser.setUser_email( request.getParameter("user_email"));
                newUser.setUser_password( request.getParameter("user_password"));

//                 dao操作
                boolean b = userDao.updateLoginUser(newUser);
                User user = userDao.GetUserById(id);


                String json = gson.toJson(user);
                 LOGGER.debug("    json:"+json);
                 response.getWriter().println(json);
                break;
            }
            default:{

            }
        }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
